import modelExtend from 'dva-model-extend'
import { query, enable, disable, addUser, syncUser } from 'services/security/user'
import { getUserRoles, bindUserRoles } from 'services/security/role'
import { getUserOrganizations, bindOrgs } from 'services/organization'
import { queryUserByKeywords } from 'services/security/user'
import { lwjPageModel } from 'utils/model'
import { routerRedux } from 'dva/router'
import { Modal } from 'antd'
import { config } from 'utils'

export default modelExtend(lwjPageModel, {
  namespace: 'user',
  state: {
    visible: false,
    addState: false,
    roles: [],
    pageOptions: {
      sort: 'createTime',
      order: 'DESC'
    },
    isExpand: false,
    queryParam: {},
    roleIds: [],
    showBindRolesModal: false,
    userId: '',
    organizationIds: [],
    showBindOrganizationModal: false,
    loadingStatus: false,
    type:"add"
  },
  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(({ pathname }) => {
        if (pathname === '/user') {
          dispatch({ type: 'query', payload: {} })
        }
      })
    }
  },
  effects: {
    * query({
      payload
    }, { select, call, put }) {
      yield put({
        type: 'asyncData',
        payload: {
          ...payload
        }
      })
      const pageOptions = yield select(({ user }) => user.pageOptions)
      const queryParam = yield select(({ user }) => user.queryParam)
      const queryPayload = {
        ...pageOptions,
        queryParam: {
          ...queryParam
        }
      }
      const data = yield call(query, queryPayload)
      yield put({
        type: 'querySuccess',
        payload: {
          ...data
        }
      })
    },
    * onEnabled({
      payload
    }, { select, call, put }) {
      const queryParam = yield select(({ user }) => user.queryParam)
      yield call(enable, payload)
      Modal.success({
        title:"启用成功",
        content:"启用用户成功"
      })
      yield put({
        type: 'query',
        payload: {
          ...queryParam
        }
      })
    },
    * getUserRoles({
      payload
    }, { select, call, put }) {
      const data = yield call(getUserRoles, payload)
      yield put({
        type: 'showUserRoles',
        payload: {
          roles: data.result,
          roleIds: data.result.map(item => item.id),
          userId: payload
        }
      })
    },
    * getUserOrganizations({
      payload
    }, { select, call, put }) {
      const data = yield call(getUserOrganizations, payload)
      yield put({
        type: 'showUserRoles',
        payload: {
          organizationIds: data.result.map(item => item.id),
          userId: payload
        }
      })
    },
    * onDisabled({
      payload
    }, { select, call, put }) {
      const queryParam = yield select(({ user }) => user.queryParam)
      yield call(disable, payload)
      Modal.success({
        title:"禁用成功",
        content:"禁用用户成功"
      })
      yield put({
        type: 'query',
        payload: {
          ...queryParam
        }
      })
    },
    * syncUser({
      payload
    }, { select, call, put }) {
      const data = yield call(syncUser,payload)
      if (data.code === 0) {
        Modal.success({
          title: '同步成功',
          content: '同步更新用户成功！'
        })
        yield put({
          type: 'showUserAdd',
          payload: {
            isShow: false
          }
        })
        yield put(routerRedux.push(`/user`))

      }
    },
    * addUser({
      payload
    }, { select, call, put }) {
      const data = yield call(addUser, payload)
      if (data.result === 'unExist') {
        Modal.error({
          title: '请求出错了',
          content: (
            <div>
              <p>丽维家找不到该用户，请检查确认。</p>
              <p><a href={config.REGISTER_URL} target="_Blank">点我注册</a></p>
            </div>)
        })
      } else {
        yield put(routerRedux.push(`/user`))
        yield put({
          type: 'showUserAdd',
          payload: {
            isShow: false
          }
        })
      }
    },
    * findUser({
      payload
    }, { select, call, put }) {
      const res = yield call(queryUserByKeywords, payload.keyword)
      if (!res.success) {
        Modal.error({
          title: '请求出错了',
          content: (
            <div>
              <p>丽维家找不到该用户，请检查确认。</p>
              <p><a href={config.REGISTER_URL} target="_Blank">点我注册</a></p>
            </div>)
        })
      } else {
        yield put(routerRedux.push(`/user`))
        yield put({
          type: 'showUserAdd',
          payload: {
            isShow: false
          }
        })
      }
    },
    * onBindRoles({ payload }, { call, put }) {
      const { userId, roleIds } = payload
      const res = yield call(bindUserRoles, userId, roleIds)
      if (res.success) {
        yield put({
          type: 'showUserRolesModal',
          payload: false
        })
      }
    },
    * onBindOrganizations({ payload }, { call, put }) {
      const { userId, organizationIds } = payload
      const res = yield call(bindOrgs, userId, organizationIds)
      if (res.success) {
        yield put({
          type: 'showUserOrganizationsModal',
          payload: false
        })
      }
    },
  },
  reducers: {
    showUserAdd(state, { payload }) {
      return {
        ...state,
        visible: payload.isShow
      }
    },
    showUserRoles(state, { payload }) {
      return {
        ...state,
        ...payload,
      }
    },
    emptyUserRoles(state, { payload }) {
      return {
        ...state,
        roles: []
      }
    },
    showUserRolesModal(state, { payload }) {
      return {
        ...state,
        showBindRolesModal: payload
      }
    },
    showUserOrganizationsModal(state, { payload }) {
      return {
        ...state,
        showBindOrganizationModal: payload
      }
    },
    bindSelectedIds(state, { payload }) {
      return {
        ...state,
        ...payload
      }
    },
    setLoadingStatus(state, payload) {
      return {
        ...state,
        loadingStatus: payload.payload
      }
    },
    setType(state, payload) {
      console.info(payload)
      return {
        ...state,
        type: payload.payload
      }
    },
  }
})
